package tt.dz.egobus.servicemanager.base.controller;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import tt.dz.egobus.servicemanager.core.resovler.ClassReflactParamConvert;
import tt.dz.egobus.servicemanager.core.resovler.ParamConvert;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author Anson
 * @date 17-3-15
 * @name 常用的属性转换器
 * @since 1.0.1
 */
public abstract class CommonBinderController {

    /**
     * 排除过滤的key,即不需要的key
     */
    public static final String[] EXCLUDE = {"_dc"};

    private static final ParamConvert<ClassReflactParamConvert.ConvertEntity> CONVERT =
            new ClassReflactParamConvert();

    /**
     * @param params 带有查询功能key
     * @author Anson
     * @date 17-3-16
     * @name 转换其中参数对象的类型转换；例如;int@eq#anson=123432 就会转换成int类型的对象
     * @since 1.0.1
     */
    protected Map<String, Object> convertParams(Map<String, Object> params) {
        Map.Entry<String, Object> entry = null;
        String key = null;
        Object value = null;
        Object[] values = null;
        String convertedKey = null;
        ClassReflactParamConvert.ConvertEntity convertEntity = null;
        Map<String, Object> paramsConverted = new HashMap(params.size());
        for (Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator();
             iterator.hasNext(); ) {
            entry = iterator.next();
            key = entry.getKey();
            if (ArrayUtils.contains(EXCLUDE, key)) {
                continue;
            }
            value = entry.getValue();

            if (value.getClass().isArray()) {
                String[] array = ((String[]) value);
                if (array == null || array.length == 0) {
                    continue;
                }
                values = new Object[array.length];
                int i = 0;
                for (String v : array) {
                    convertEntity = CONVERT.convert(key, v);
                    values[i] = convertEntity == null ? v : convertEntity.getValue();
                    convertedKey = convertEntity == null ? key : convertEntity.getOpKey();
                    i++;
                }
                value = values;
            } else {
                if (StringUtils.isBlank(value.toString())) {
                    continue;
                }
                convertEntity = CONVERT.convert(key, value.toString());
                value = convertEntity == null ? value : convertEntity.getValue();
                convertedKey = convertEntity == null ? key : convertEntity.getOpKey();
            }
            paramsConverted.put(convertedKey, value);
        }
        params.clear();
        return paramsConverted;
    }


}
